<?php

namespace app\admin\controller\user;

use app\admin\controller\Base;
use app\common\model\user\UserLabelModel;

class Label extends Base
{
    /**
     * 标签列表
     */
    public function list()
    {
        $params = request()->only(['page', 'limit', 'name']);

        if (isset($params['name']) && !empty($params['name'])) {
            $where[] = ['name', 'like', "%{$params['name']}%"];
        }

        $list = (new UserLabelModel)->where($where ?? [])->paginate([
            'list_rows' => $params['limit'] ?? 10,
            'page' => $params['page'] ?? 1
        ]);

        return response_success('', [
            'count' => $list->total(),
            'data' => $list->items()
        ]);
    }

    /**
     * 添加标签
     */
    public function add()
    {
        $params = request()->only(['name']);
        $this->validate($params, [
            'name|名称' => 'require'
        ]);

        if ((new UserLabelModel)->where('name', $params['name'])->find()) {
            return response_error('名称已存在');
        }

        (new UserLabelModel)->insert([
            'name' => $params['name'],
            'create_time' => date('Y-m-d H:i:s'),
            'create_admin_id' => $this->adminInfo['id']
        ]);

        return response_success();
    }

    /**
     * 删除标签
     */
    public function del()
    {
        $params = request()->only(['ids']);
        $this->validate($params, [
            'ids' => 'require'
        ], [
            'ids.require' => '请选择删除标签'
        ]);

        $userLabelModel = new UserLabelModel;
        if (!$userLabelModel->delLabel($params['ids'])) {
            return response_error($userLabelModel->getError());
        }

        return response_success();
    }

    /**
     * 编辑标签
     */
    public function edit()
    {
        $params = request()->only(['id', 'name']);
        $this->validate($params, [
            'id' => 'require',
            'name|标签名称' => 'require'
        ]);

        if ((new UserLabelModel)->where('id', '<>', $params['id'])->where('name', $params['name'])->find()) {
            return response_error('标签名称已存在');
        }

        (new UserLabelModel)->where('id', $params['id'])->update([
            'name' => $params['name'],
            'update_time' => date('Y-m-d H:i:s')
        ]);

        return response_success();
    }

    /**
     * 所有标签
     */
    public function getAll()
    {
        $params = request()->only(['name']);

        if (isset($params['name']) && !empty($params['name'])) {
            $where[] = ['name', 'like', "%{$params['name']}%"];
        }
        $list = (new UserLabelModel)->where($where ?? [])->select()->toArray();

        return response_success('', $list);
    }

}